// ============================================================================
//
// Copyright (C) 2006-2007 Dengues
//
// Google Group: http://groups.google.com/group/dengues
// QQ Group: 24885404
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// ============================================================================
package org.dengues.designer.ui.wizards;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;

import org.dengues.designer.ui.database.editors.GEFDatabaseEditor;
import org.dengues.designer.ui.i18n.Messages;
import org.dengues.model.DenguesModelManager;
import org.dengues.model.database.DatabaseDiagram;
import org.eclipse.core.resources.IFile;
import org.eclipse.emf.ecore.xmi.XMLResource;
import org.eclipse.emf.ecore.xmi.impl.XMLResourceImpl;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.dialogs.WizardNewFileCreationPage;
import org.eclipse.ui.ide.IDE;

public class CreationDBEditorPage extends WizardNewFileCreationPage {

    private static int fileCount = 1;

    private IWorkbench workbench;

    public CreationDBEditorPage(IWorkbench workbench, IStructuredSelection selection) {
        super(Messages.getString("CreationDBEditorPage.0"), selection); //$NON-NLS-1$
        this.workbench = workbench;
        setTitle(Messages.getString("CreationDBEditorPage.Wizard.Title", GEFDatabaseEditor.DEFAULT_EXTENSION //$NON-NLS-1$
                ));
        setDescription(Messages.getString("CreationDBEditorPage.Wizard.Title", GEFDatabaseEditor.DEFAULT_EXTENSION //$NON-NLS-1$
                ));
    }

    @Override
    public void createControl(Composite parent) {
        super.createControl(parent);
        setFileName("dbe" + fileCount + GEFDatabaseEditor.DEFAULT_EXTENSION); //$NON-NLS-1$
        setPageComplete(validatePage());
    }

    /** Return a new DatabaseDiagram instance. */
    private Object createDefaultContent() {
        return DenguesModelManager.getDatabaseFactory().createDatabaseDiagram();
    }

    private DatabaseDiagram diagram;

    @SuppressWarnings("unchecked") //$NON-NLS-1$
    @Override
    protected InputStream getInitialContents() {
        diagram = (DatabaseDiagram) createDefaultContent();
        XMLResource resource = new XMLResourceImpl();
        resource.getContents().add(diagram);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            resource.save(out, Collections.EMPTY_MAP);
        } catch (IOException e) {
            e.printStackTrace();
        }
        ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
        return in;
    }

    private boolean validateFilename() {
        if (getFileName() != null && getFileName().endsWith(GEFDatabaseEditor.DEFAULT_EXTENSION)) {
            return true;
        }
        setErrorMessage(Messages.getString("CreationDBEditorPage.Error", GEFDatabaseEditor.DEFAULT_EXTENSION)); //$NON-NLS-1$
        return false;
    }

    protected boolean validatePage() {
        return super.validatePage() && validateFilename();
    }

    public boolean finish() {
        // create a new file, result != null if successful
        IFile newFile = createNewFile();
        fileCount++;

        // open newly created file in the editor
        IWorkbenchPage page = workbench.getActiveWorkbenchWindow().getActivePage();
        if (newFile != null && page != null) {
            try {
                IDE.openEditor(page, newFile, true);
            } catch (PartInitException e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    public DatabaseDiagram getDBDiagram() {
        return this.diagram;
    }

}
